package com.peng.sta.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.peng.base.exception.GuliException;
import com.peng.sta.client.UserClient;
import com.peng.sta.entity.StatisticsDaily;
import com.peng.sta.mapper.StatisticsDailyMapper;
import com.peng.sta.service.StatisticsDailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author Dengp
 * @since 2022-06-25
 */
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {
    @Autowired
    private UserClient userClient;
    //根据日期统计当天注册人数
    @Override
    public void countRegister(String day) {
        int registerCount = userClient.getRegisterCount(day);
        LambdaQueryWrapper<StatisticsDaily> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StatisticsDaily::getDateCalculated,day);
        this.remove(queryWrapper);
        StatisticsDaily statisticsDaily = new StatisticsDaily();
        statisticsDaily.setDateCalculated(day);
        statisticsDaily.setRegisterNum(registerCount);
        statisticsDaily.setCourseNum(RandomUtils.nextInt(100,200));
        statisticsDaily.setLoginNum(RandomUtils.nextInt(100,200));
        statisticsDaily.setVideoViewNum(RandomUtils.nextInt(100,200));
        this.saveOrUpdate(statisticsDaily);
    }

    //根据时期统计人数
    @Override
    public Map<String, Object> showData(String type, String begin, String end) {
        if (type==null || begin==null|| end==null){
            throw new GuliException(20001,"参数不齐");
        }
        QueryWrapper<StatisticsDaily> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("date_calculated",begin,end);
        queryWrapper.select("date_calculated",type);
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);
        ArrayList dateLists = new ArrayList<>();
        ArrayList numLists = new ArrayList<>();
        maps.stream().forEach(item->{
            dateLists.add(item.get("date_calculated"));
            numLists.add(item.get(type));
        });
        HashMap<String, Object> map = new HashMap<>();
        map.put("datalist",dateLists);
        map.put("numlist",numLists);
        return map;
    }
}
